/**
 * 请求处理
 */
import querystring from 'qs';
import axios from 'axios';
export default function requerst(app) {
  const { adapter = undefined, baseURL = '' } = app.options.configureAxios || Object.create(null);
  const $http = axios.create({
    baseURL,
    timeout: 8000, // 请求超时时间
    adapter
  });

  function installUrl(url, params) {
    return `${url}${params && Object.keys(params).length ? `${url.indexOf('?') > -1 ? '&' : '?'}${querystring.stringify(params)}` : ''}`;
  }

  function consoleLog(type, tag, config, err) {
    const method = config.method.toLocaleUpperCase();
    app.logger[type](`${tag} ${type.toLocaleUpperCase()}:: TIME:${Date.now() - config.startTime}ms, METHOD:${method}, URL:${installUrl(config.url, config.params)} ,DATA:${querystring.stringify(config.data)}`, err && err.message);
  }

  // 添加拦截器，将产品id添加到请求上
  $http.interceptors.request.use(config => {
    const method = config.method.toLocaleUpperCase();
    if (method === 'GET') {
      delete config.data;
      config.params = Object.assign({}, config.params);
    } else {
      config.data = Object.assign({}, config.params, config.data);
      const contentType = config.headers['content-type'];
      if (contentType && contentType.includes('application/x-www-form-urlencoded')) {
        config.data = querystring.stringify(config.data);
      }
    }

    // 记录开始时间
    config.startTime = Date.now();
    consoleLog('log', 'REQUEST', config);
    return config;
  }, err => {
    consoleLog('error', 'REQUEST', err.config, err);
    return Promise.reject(err);
  });

  $http.interceptors.response.use(res => {
    const config = res.config;
    consoleLog('log', 'RESPONSE', res.config);
    const resData = res.data;
    const { extra = {} } = config;
    if (extra.result && resData.status === 0) {
      return resData.data;
    }
    return resData;
  }, err => {
    consoleLog('error', 'RESPONSE', err.config, err);
    return Promise.reject(err);
  });

  // 添加公共拦截器
  $http.interceptors.request.use(config => {
    const { extra = {} } = config;
    if (extra.auth) {
      const state = reduxStore.getState();
      const { user: { userInfo } } = state;
      if (userInfo && userInfo.token) {
        config.headers = {
          'Authorization': `Bearer ${userInfo.token}`,
          ...config.headers
        }
      } else {
        let err = new Error('没有找到token');
        err.config = config;
        consoleLog('error', 'REQUEST', config, err);
        return Promise.reject(err);
      }
    }
    return config;
  });
  return $http;
};
